//
//  DrawViewController.swift
//  SwiftProject
//
//  Created by HBY on 2021/5/6.
//

import UIKit
import SnapKit
import Toast_Swift

class DrawViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
    @IBOutlet weak var layoutTop_h: NSLayoutConstraint!//50 || 100
    @IBOutlet weak var imgBg: UIImageView!
    @IBOutlet weak var numberTxt: UILabel!
    @IBOutlet weak var topSegment: UISegmentedControl!
    @IBOutlet weak var drawView: UIView!
    @IBOutlet weak var imgSegment: UISegmentedControl!
    
    @IBOutlet weak var pickerView: UIView!
    @IBOutlet weak var pickerBtn: UIButton!
    @IBOutlet weak var mCollectView: UICollectionView!
    
    let imgView:UIImageView = UIImageView()//橡皮擦
    var edColor:UIColor?//当前颜色
    var edIndex:Int = 0//颜色下标
    var edImgIndex:Int = 0//选择图片下标
    var isShow:Bool = false//显示选择器
    
    var startPoint:CGPoint?
    var endPoint:CGPoint?
    var layers:Array<CALayer> = []
    var sealImages:Array<UIImageView> = []
    var colors:Array<UIColor> = [UIColor.white, UIColor.red,UIColor.green,
                                 UIColor.blue,UIColor.gray,UIColor.yellow,
                                 UIColor.black,UIColor.orange,UIColor.systemBlue]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "画板"
//        self.navigationController?.navigationBar.isTranslucent = false
        
        let customBtn = UIButton.init(type: .custom)
        customBtn.frame = CGRect.init(x: 0, y: 0, width: 50, height: 50)
        customBtn.setTitle("保存", for: .normal)
        customBtn.setTitleColor(UIColor.black, for: .normal)
        customBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        customBtn.addTarget(self, action: #selector(saveImageData), for: .touchUpInside)
        let rightBtn = UIBarButtonItem.init(customView: customBtn)
        self.navigationItem.rightBarButtonItem = rightBtn
        
        imgView.isUserInteractionEnabled = true
        imgView.image = UIImage.init(named: "ic_eraser")
        imgView.isHidden = true
        view.addSubview(imgView)
        imgView.snp.makeConstraints { make in
            make.width.equalTo(40)
            make.height.equalTo(40)
            make.centerY.equalTo(view)
            make.centerX.equalTo(view)
        }
        
        imgBg.isHidden = true
        imgSegment.isHidden = true
        pickerView.transform = CGAffineTransform(translationX: 0, y: -60)
        
        let mLayout = UICollectionViewFlowLayout()
        mLayout.scrollDirection = .horizontal
        mLayout.itemSize = CGSize.init(width: 50, height: 50)
        mLayout.headerReferenceSize = CGSize.init(width: 10, height: 10)
        mLayout.footerReferenceSize = CGSize.init(width: 10, height: 10)
        
        mCollectView.collectionViewLayout = mLayout;
        mCollectView.delegate = self
        mCollectView.dataSource = self
        // Do any additional setup after loading the view.
    }
    
    @objc func click_update() {
        let animation:CAKeyframeAnimation = CAKeyframeAnimation()
        animation.keyPath = "transform.scale"
        animation.values = [0.9,1.1,0.8,1.0]
        animation.duration = 0.3
        animation.calculationMode = .paced
        animation.autoreverses = true
        animation.repeatCount = 3
        imgView.layer.add(animation, forKey: "")
        
        let temp_y = CGFloat(arc4random()%200+200)
        let temp_x = CGFloat(arc4random()%300)
        
        var rc = imgView.frame
        var start = rc.origin
        start.y = start.y + 20
        start.x = start.x + 20
        
        rc.origin.y = temp_y
        rc.origin.x = temp_x
        
        var end = rc.origin
        end.y = end.y + 20
        end.x = end.x + 20
        
        UIView.animate(withDuration: 0.35) {
            self.imgView.frame = rc
        }completion: { Bool in
            self.drawLineFrom(fromPoint: start, toPoint: end)
        }
    }
    
    func imageForIndex(_ index:Int) -> String {
        var nameStr = "icon_sg\(index)";
        switch imgSegment.selectedSegmentIndex {
        case 1:
            nameStr = "icon_rw\(index)";
            break
        case 2:
            nameStr = "icon_jt\(index)";
            break
        case 3:
            nameStr = "icon_zw\(index)";
            break
        case 4:
            nameStr = "icon_dw\(index)";
            break
        case 5:
            nameStr = "icon_fz\(index)";
            break
        case 6:
            nameStr = "icon_hy\(index)";
            break
        default: break
        }
        
        return nameStr
    }
    
    @objc func saveImageData() {
        var mImage = UIImage()
        UIGraphicsBeginImageContextWithOptions(drawView.frame.size, true, UIScreen.main.scale)
        drawView.layer.render(in: UIGraphicsGetCurrentContext()!)
        mImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        
        //UIImageWriteToSavedPhotosAlbum(mImage, self,nil, nil)
        self.view.makeToast("保存成功")
        
        let imageData: NSData = mImage.jpegData(compressionQuality: 1)! as NSData
        let fullPath = NSHomeDirectory().appending("/Documents/").appending("\(Int(NSDate.init().timeIntervalSince1970)).png")
        imageData.write(toFile: fullPath, atomically:true)
    }
    
    //MARK: - UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        if topSegment.selectedSegmentIndex == 4 {
            return 6
        }
        else if topSegment.selectedSegmentIndex == 3 {//图片选择
            var defNum = 13;
            switch imgSegment.selectedSegmentIndex {
            case 1:
                defNum = 28
                break
            case 2:
                defNum = 22
                break
            case 3:
                defNum = 14
                break
            case 4:
                defNum = 25
                break
            case 5:
                defNum = 21
                break
            case 6:
                defNum = 27
                break
            default: break
            }
            
            return defNum
        }
        else{//颜色选择
            return colors.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        let cell:ColorCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColorCollectionCell", for: indexPath) as! ColorCollectionCell
        
        if topSegment.selectedSegmentIndex == 4 {//图片选择
            cell.colorView.backgroundColor = UIColor.white
            cell.edImage.isHidden = true
            cell.colorImage.isHidden = false
            cell.colorImage.image = UIImage.init(named: "bg\(indexPath.row)")
        }
        else if topSegment.selectedSegmentIndex == 3 {//图片选择
            cell.colorView.backgroundColor = UIColor.white
            cell.edImage.isHidden = indexPath.row != edImgIndex
            cell.colorImage.isHidden = false
            cell.colorImage.image = UIImage.init(named: imageForIndex(indexPath.row))
        }
        else{//颜色选择
            cell.colorView.backgroundColor = colors[indexPath.row]
            cell.edImage.isHidden = indexPath.row != edIndex
            cell.colorImage.isHidden = indexPath.row != 0;//非首个颜色就隐藏
            cell.colorImage.image = UIImage.init(named: "more_color")
        }
        
        return cell;
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        if topSegment.selectedSegmentIndex <= 1 {//辐射线、画线
            edIndex = indexPath.row
            edColor = colors[edIndex]
        }
        else if topSegment.selectedSegmentIndex == 3 {//图片选择
            edImgIndex = indexPath.row
        }
        else if topSegment.selectedSegmentIndex == 4 {//背景图选择
            imgBg.isHidden = false
            imgBg.image = UIImage.init(named: "bg\(indexPath.row)")
        }
        
        collectionView.reloadData()
    }
    
    //MARK: - onclick
    @IBAction func onclick_clear() {
        for layer in layers {
            layer.removeFromSuperlayer()
        }
        
        sealImages.forEach { tView in
            tView.removeFromSuperview()
        }
        
        //删除所有
        layers.removeAll()
        sealImages.removeAll()
    }
    
    @IBAction func onclick_picker() {
        isShow = !isShow
        
        if isShow {
            mCollectView.reloadData()//刷新数据
            
            UIView.animate(withDuration: 0.35) {
                self.pickerView.transform = CGAffineTransform(translationX: 0, y: 0)
                self.pickerBtn.transform = CGAffineTransform(rotationAngle: .pi)
            }
        }
        else {
            UIView.animate(withDuration: 0.35) {
                self.pickerView.transform = CGAffineTransform(translationX: 0, y: -60)
                self.pickerBtn.transform = CGAffineTransform(rotationAngle: .pi * 2)
            }
        }
    }
    
    @IBAction func onclick_add() {
        let str = numberTxt.text ?? "0"
        numberTxt.text = "\(Int(str)!+1)"
    }
    
    @IBAction func onclick_subtract() {
        let str = numberTxt.text ?? "0"
        let num = Int(str) ?? 1
        if num <= 1 {
            return
        }
        
        numberTxt.text = "\(num-1)"
    }
    
    @IBAction func image_change() {
        edImgIndex = 0
        
        //未显示
        if !isShow {
            onclick_picker()//显示选择view
        }
        else{
            mCollectView.reloadData()
        }
    }
    
    @IBAction func statusChange() {
        if topSegment.selectedSegmentIndex <= 1 {//辐射线、画线
            self.imgSegment.isHidden = true
            layoutTop_h.constant = 100;
            
            //未显示
            if !isShow {
                onclick_picker()//显示选择view
            }
            else {
                mCollectView.reloadData()
            }
        }
        else if topSegment.selectedSegmentIndex == 2 {//橡皮擦
            self.imgSegment.isHidden = false
            layoutTop_h.constant = 55;
            
            //显示
            if isShow {
                onclick_picker()//不显示选择view
            }
        }
        else if topSegment.selectedSegmentIndex == 3 {//印章
            self.imgSegment.isHidden = false
            layoutTop_h.constant = 100;
            
            //未显示
            if !isShow {
                onclick_picker()//显示选择view
            }
            else {
                mCollectView.reloadData()
            }
        }
        else if topSegment.selectedSegmentIndex == 4 {//背景图
            layoutTop_h.constant = 55;
            
            //未显示
            if !isShow {
                onclick_picker()//显示选择view
            }
            else {
                mCollectView.reloadData()
            }
        }
    }
    
    //MARK: - touch
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if isEditing {
            return
        }
        
        let t:UITouch = touches.first!
        startPoint = t.location(in: view)
        
        let tIndex = topSegment.selectedSegmentIndex
        if tIndex == 3 {//印章
            let tempImg = UIImageView()
            tempImg.isUserInteractionEnabled = true
            tempImg.image = UIImage.init(named: imageForIndex(edImgIndex))
            //tempImg.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(dragMethod)))//拖动
            //tempImg.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapMethod)))//点击
            drawView.addSubview(tempImg)
            sealImages.append(tempImg)
            tempImg.snp.remakeConstraints { make in
                make.width.equalTo(80)
                make.height.equalTo(80)
                make.centerX.equalTo(startPoint?.x ?? 0)
                make.centerY.equalTo(startPoint?.y ?? 0)
            }
        }
        else if tIndex == 2 {//橡皮擦
            imgView.isHidden = false
            imgView.snp.remakeConstraints { make in
                make.width.equalTo(40)
                make.height.equalTo(40)
                make.centerX.equalTo(startPoint?.x ?? 0)
                make.centerY.equalTo(startPoint?.y ?? 0)
            }
        }
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let tIndex = topSegment.selectedSegmentIndex
        
        if tIndex == 3 {//印章
            
        }
        else if tIndex == 0{//辐射线
            let t:UITouch = touches.first!
            endPoint = t.location(in: view)
            drawLineFrom(fromPoint: startPoint!, toPoint: endPoint!)
        }
        else {//画线、橡皮擦
            for t in touches {
                endPoint = t.location(in: view)
                
                drawLineFrom(fromPoint: startPoint!, toPoint: endPoint!)
                startPoint = endPoint
            }
        }
        print("拖动-------")
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let tIndex = topSegment.selectedSegmentIndex
        if tIndex == 2 {//橡皮擦
            imgView.isHidden = true
        }
        
        isEditing = false
    }
    
    @objc func dragMethod(recognizer:UIGestureRecognizer) {
        //更新位置
        recognizer.view?.center = recognizer.location(in: drawView)
    }
    
    @objc func tapMethod(recognizer:UIGestureRecognizer) {
        isEditing = true
    }
    
    func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {
        let path = UIBezierPath()
        path.move(to: fromPoint)
        path.addLine(to: toPoint)
        
        let str = numberTxt.text ?? "1"
        let double = Double(str)
        
        var mWidth = CGFloat(double ?? 0)
        let temoColor:UIColor
        if topSegment.selectedSegmentIndex == 2 {//橡皮擦
            temoColor = UIColor.white
            mWidth = 40
            imgView.snp.remakeConstraints { make in
                make.width.equalTo(40)
                make.height.equalTo(40)
                make.centerY.equalTo(toPoint.y)
                make.centerX.equalTo(toPoint.x)
            }
        }
        else if(edIndex > 0){//单一颜色
            temoColor = edColor!
        }
        else {//多颜色
            let red = CGFloat(arc4random()%256)/255.0
            let green = CGFloat(arc4random()%256)/255.0
            let blue = CGFloat(arc4random()%256)/255.0
            temoColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
        }
        
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.strokeColor = temoColor.cgColor
        shapeLayer.lineWidth = mWidth
        drawView.layer.addSublayer(shapeLayer)
        layers.append(shapeLayer)
    }
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
}
